package base.service.impl;

import base.mapper.IPlogMapper;
import base.pojo.IPlog;
import base.query.IPLogQuery;
import base.service.ILoginInfoService;
import base.service.IiPlogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import common.Const;
import common.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.DataSourceContext;
import util.PageUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IPlogServiceImpl implements IiPlogService
{

    @Autowired
    IPlogMapper         iPlogMapper         ;
    @Autowired
    ILoginInfoService   iLoginInfoService   ;
    public void save(IPlog iPlog)
    {
        iPlogMapper.insert(iPlog);
    }


    public Map getErrorLog(String userName)
    {
        DataSourceContext.set(Const.SLAVE_DS);
        //获取最近一次成功登录的时间
        Map     map     =   iPlogMapper.getErrorLog(userName);
        if(map==null)
        {
            //第一次登录
            map =   new HashMap();
        }
        map.put("isSuccess",true)                            ;
        Integer number  = (Integer) map.get("errorNumber"   );
        Date    oldTime = (Date)    map.get("loginTime"     );
        //密码输入错误次数达到五次
        if (number != null && number >= 5)
        {
            Date newTime= new Date()                         ;
            long time   = newTime.getTime()-oldTime.getTime();
            time =time/(1000*60*60);//计算出时间差
            System.out.println(time);
            if(time<3)
            {
                map.put("isSuccess",false)                   ;
                map.put("msg","该账号密码输入次数过多,已被冻结三个小时,请稍后再尝试登录");
            }
        }
        return map;
    }

    public PageInfo<IPlog> getAllIPLogByLimit(IPLogQuery ipLogQuery)
    {
        DataSourceContext.set(Const.SLAVE_DS);
        if(ipLogQuery.getPageNum()  ==  null  ||  ipLogQuery.getPageNum()  <  1)
        {
            ipLogQuery.setPageNum(1)    ;
        }
        if(ipLogQuery.getPageSize() == null)
        {
            ipLogQuery.setPageSize(10)  ;
        }
        PageHelper.startPage(ipLogQuery.getPageNum()                            ,
                ipLogQuery.getPageSize()).setOrderBy("loginTime DESC")          ;
        ipLogQuery.setUserName(UserContext.getCurrentUser().getUsername())      ;
        List<IPlog>     list        =   iPlogMapper.selectAllById(ipLogQuery)   ;
       return PageUtil.returnPageInfo(list)                                     ;
    }
}
